
package com.eportal.action.background;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.CRoom;
import com.eportal.domain.Sysopt;
import com.eportal.domain.Sysroles;
import com.eportal.domain.TuserWallet;
import com.eportal.service.CBuildingService;
import com.eportal.service.CInstallUnitService;
import com.eportal.service.CRoomService;
import com.eportal.service.RedEnvService;
import com.eportal.service.UserWalletService;
import com.eportal.util.MdExpiringMap;
import com.eportal.util.UploadUtil;
import com.eportal.util.WebUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;



/**
 * 房间管理
 *
 */
public class RedEnvAction extends BaseAction implements ModelDriven<CRoom> {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Logger log = Logger.getLogger(CRoomAction.class);

    private Map<String, Object> result = new HashMap<String, Object>();
    
    @Autowired
    private CRoomService cRoomService;
    @Autowired
    private RedEnvService redEnvService;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private CInstallUnitService cInstallUnitService;
    @Autowired
    private CBuildingService cBuildingService;

    private static MdExpiringMap<String, String> randomMap = new MdExpiringMap(3600,500);
    
    public String redEnvlistView() throws Exception{
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String optId = String.valueOf(user.getSid());
    	//获取进行中的红包数
    	String sql = "select count(1) renums from t_redenvmain t1,t_redenvdetail t2 where t1.sid = t2.remainid and t1.optid= '"+optId+"'"+" and t2.envstatus in ('1','2')";
    	List<Map<String, String>> list = redEnvService.listBySql(sql);
    	String redenv = String.valueOf(list.get(0).get("renums"));
    	//获取今日发放红包个数和金额
    	sql = "select count(1) todayNum,nvl(sum(t2.totalamount),0) todayAmount from t_redenvmain t1,t_redenvdetail t2 where t1.sid = t2.remainid  and t2.envstatus<>'5' and t1.optid= '"+optId+"'"+"and trunc(t1.ctime,'dd') = trunc(sysdate,'dd')";
    	List<Map<String, String>> list2 = redEnvService.listBySql(sql);
    	String todayNum = String.valueOf(list2.get(0).get("todayNum"));
    	String todayAmount = String.valueOf(list2.get(0).get("todayAmount"));
    	String balance = "";
    	try {
			TuserWallet wallet = userWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
			balance = wallet.getAmount().toString();
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			getRequest().setAttribute("msg", "获取用户钱包失败"+e.getMessage());
			return new String("exception");
		}
    	getRequest().setAttribute("balance", balance);
    	getRequest().setAttribute("valbalance", balance);
    	getRequest().setAttribute("frzbalance", "0.00");
    	getRequest().setAttribute("redenv", redenv);
    	getRequest().setAttribute("todayNum", todayNum);
    	getRequest().setAttribute("todayAmount", todayAmount);  
    	String vtype = getRequest().getParameter("vtype");
		if(vtype!=null){//打开定额、随机红包，只在第一次时打开，再次刷新页面等操作不会打开
			String random = getRequest().getParameter("random");
			if(randomMap.get(random)==null){
				getRequest().setAttribute("vtype", vtype);
				randomMap.put(random, "");
			}else{
				
			}
		}
        return SUCCESS;
    }
 
    public String receiveLog(){
        return SUCCESS;
    }
    
    public String addQuotaView(){
    	return SUCCESS;
    }

    public String addRandomView(){
    	return SUCCESS;
    }
    
    public String setTime() throws Exception{
    	String period = getRequest().getParameter("period");
    	if(period!=null&&!"".equals(period)){
        	if("1".equals(period)){
    			getRequest().setAttribute("isAllday", period);
    	    	return SUCCESS;
        	}
    		if(period.indexOf("and")>-1){
    			String period1 = period.split("and")[0];
    			String period2 = period.split("and")[1];
    			String time11 = period1.split("-")[0].split(":")[0];
    			String time12 = period1.split("-")[0].split(":")[1];
    			String time13 = period1.split("-")[1].split(":")[0];
    			String time14 = period1.split("-")[1].split(":")[1];
    			String time21 = period2.split("-")[0].split(":")[0];
    			String time22 = period2.split("-")[0].split(":")[1];
    			String time23 = period2.split("-")[1].split(":")[0];
    			String time24 = period2.split("-")[1].split(":")[1];
    			getRequest().setAttribute("time11", time11);
    			getRequest().setAttribute("time12", time12);
    			getRequest().setAttribute("time13", time13);
    			getRequest().setAttribute("time14", time14);
    			getRequest().setAttribute("time21", time21);
    			getRequest().setAttribute("time22", time22);
    			getRequest().setAttribute("time23", time23);
    			getRequest().setAttribute("time24", time24);
    		}else{
    			String time11 = period.split("-")[0].split(":")[0];
    			String time12 = period.split("-")[0].split(":")[1];
    			String time13 = period.split("-")[1].split(":")[0];
    			String time14 = period.split("-")[1].split(":")[1];
    			getRequest().setAttribute("time11", time11);
    			getRequest().setAttribute("time12", time12);
    			getRequest().setAttribute("time13", time13);
    			getRequest().setAttribute("time14", time14);
    			getRequest().setAttribute("time21", "");
    			getRequest().setAttribute("time22", "");
    			getRequest().setAttribute("time23", "");
    			getRequest().setAttribute("time24", "");
    
    		}
    	}
    	return SUCCESS;
    }  
    public String setSendList(){
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String rLevel = user.getrLevel().toString();
    	String param = "";
    	getRequest().setAttribute("rLevel", rLevel);
    	if("1".equals(rLevel)){
    		param = user.getAgtCode();
    	}
    	if("2".equals(rLevel)){
    		param = user.getCommunityId();
    	}
    	getRequest().setAttribute("prm", param);

    	return SUCCESS;
    } 
    public String detailView() throws Exception{
    	Long sid = (Long)getRequest().getAttribute("sid");
        List<Map<String, Object>> list = redEnvService.detail(sid);
        String rName = (String) list.get(0).get("rname");
        String mainreType = (String) list.get(0).get("mainretype");
        float totalAmount = Float.valueOf(String.valueOf(list.get(0).get("totalamount")));
        long totalNum = Long.valueOf(String.valueOf(list.get(0).get("totalnum")));
        int recTimes = Integer.valueOf(String.valueOf(list.get(0).get("rectimes")));
        String effectiveDate = (String) list.get(0).get("effectivedate");
        String period = (String) list.get(0).get("period");
        String adPicture = (String) list.get(0).get("adpicture");
        String cUrl = (String) list.get(0).get("curl");
    	getRequest().setAttribute("rName", rName);
    	getRequest().setAttribute("mainreType", mainreType);
    	getRequest().setAttribute("totalAmount", totalAmount);
    	getRequest().setAttribute("totalNum", totalNum);
    	getRequest().setAttribute("recTimes", recTimes);
    	getRequest().setAttribute("effectiveDate", effectiveDate);
    	getRequest().setAttribute("period", period);
    	getRequest().setAttribute("adPicture", adPicture);
    	getRequest().setAttribute("cUrl", cUrl);
        return SUCCESS;
    }
    /**
     * 红包记录列表
     */
    public  void page() throws Exception{
    	JqGridPager page = new JqGridPager();
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String optId = String.valueOf(user.getSid());
    	String rName = getRequest().getParameter("rName");
    	String mainretype = getRequest().getParameter("mainretype");
    	String envstatus = getRequest().getParameter("envstatus");
    	StringBuilder where = new StringBuilder(" t1.sid=t2.remainid and t2.sendlistid = t3.sid and t2.envstatus <> '5' and t1.optid='");
    	where.append(optId+"'");
    	if(mainretype!=null&&!"".equals(mainretype)){
        	where.append(" and t1.mainretype = '");
        	where.append(mainretype+"'");
    	}
    	if(envstatus!=null&&!"".equals(envstatus)){
        	where.append(" and t2.envstatus = '");
        	where.append(envstatus+"'");	
    	}
    	if(rName!=null&&!"".equals(rName)){
        	where.append(" and t1.rname like '%");
        	where.append(rName+"%'");	
    	}
    	page.setWhere(where.toString());
    	setPage(getRequest(), page);
    	page.setSidx("t1.ctime");
    	page.setSord("desc");
        List<Map<String, Object>> list = redEnvService.page(page);
        jqGridQueryMap(Sysroles.class, getRequest(), list, getResponse(), page);

    }

    /**
     * 红包领取记录
     */
    public  void receiveLogList() throws Exception{
    	JqGridPager page = new JqGridPager();
    	String sid = getRequest().getParameter("sid");
    	StringBuilder where = new StringBuilder(" t1.sid=t2.remainid and t2.sid = t3.reid and t1.sid='");
    	where.append(sid+"'");
    	page.setWhere(where.toString());
    	setPage(getRequest(), page);
    	page.setSidx("t3.retime");
    	page.setSord("desc");
        List<Map<String, Object>> list = redEnvService.logList(page);
        jqGridQueryMap(Sysroles.class, getRequest(), list, getResponse(), page);

    }
        
    //激活红包
    public String activeRedenv() throws Exception{
    	String redEnvId = getRequest().getParameter("redEnvId");
    	result = new HashMap<String, Object>();
    	result = redEnvService.activeRedenv(redEnvId);
    	if((Integer)result.get("code")==1){
    		return "paySuccess";
    	}
    	return ERROR;
    }
 
    //激活红包外部通知地址
    public String activeRedenvOut() throws Exception{
    	String redEnvId = getRequest().getParameter("redEnvId");
    	result = new HashMap<String, Object>();
    	result = redEnvService.activeRedenv(redEnvId);
    	if((Integer)result.get("code")==1){
    		return "paySuccess";
    	}
    	return ERROR;
    }
        /**
         * 下架
         */
        public void off() throws Exception{
        	String sid  = getRequest().getParameter("sid");
       		Sysopt opt = (Sysopt) getSession().getAttribute("user");
        	result = new HashMap<String, Object>();
        	try{
        		result = redEnvService.offMethod(Long.valueOf(sid),opt);
        	}catch (Exception e){
        		 log.info(e.getMessage());
		   		 result.put("code", 0);
		         result.put("msg", "下架红包失败");
        	}
        	responseBody(result);
        }
        //红包图片保存路径    
        final static String REDENVPICPATH="/upload/redenv/";
       public String validateParm(String rName,String totalAmount,String totalNum,String reTimes,
    		   String effectiveDate,String isAllday,String isSendAll,String mainReType){
    	   String rst = "";
   		if("".equals(rName)||rName==null){
   				rst = "红包名称不能为空";
   				return rst;
	         }
		if(rName.length()>8){
				rst = "红包名称不能超过8个字符";
				return rst;
	         }
		if("".equals(totalAmount)||totalAmount==null){
				rst = "红包金额不能为空";
				return rst;
		}
		if(!isNumeric(totalAmount)){
				rst = "请输入正确的红包金额";
				return rst;
		}
		if("".equals(totalNum)||totalNum==null){
				rst = "红包个数不能为空";
				return rst;
		}
		if(!isNumeric(totalNum)){
				rst = "请输入正确的红包个数";
				return rst;
		}		
		if("".equals(reTimes)||reTimes==null){
				rst = "红包领取次数不能为空";
				return rst;
		}
		if(!isNumeric(reTimes)){
				rst = "请输入正确的红包领取次数";
				return rst;
		}
		if("".equals(effectiveDate)||effectiveDate==null){
				rst = "红包有效期不能为空";
				return rst;
		}
		if(!isNumeric(effectiveDate)){
				rst = "请输入正确的红包有效期";
				return rst;
		}
		if("".equals(isAllday)||isAllday==null){
				rst = "红包发送时间不能为空";
				return rst;
		}
		if("".equals(isSendAll)||isSendAll==null){
				rst = "红包发放对象不能为空";
				return rst;
		}
		if("".equals(mainReType)||mainReType==null){
				rst = "红包类型不能为空";
				return rst;
		}
		return rst;
       }
       public void addRedEnv() throws Exception{
       		result = new HashMap<String, Object>();
       		Sysopt opt = (Sysopt) getSession().getAttribute("user");
       		String rName = getRequest().getParameter("rName");
       		String Amount = getRequest().getParameter("Amount");
       		String totalNum = getRequest().getParameter("totalNum");
       		String reTimes = getRequest().getParameter("reTimes");
       		String effectiveDate = getRequest().getParameter("effectiveDate");
       		String period = getRequest().getParameter("period");
       		String isAllday = getRequest().getParameter("isAllday");
       		String isSendAll = getRequest().getParameter("isSendAll");
       		String agentCodes = getRequest().getParameter("agentCodes");
       		String communityIds = getRequest().getParameter("communityIds");
       		String buildingIds = getRequest().getParameter("buildingIds");
       		String unitIds = getRequest().getParameter("unitIds");
       		String roomIds = getRequest().getParameter("roomIds");
       		String mainReType = getRequest().getParameter("mainReType");
       		String cUrl = getRequest().getParameter("cUrl");
       		String adPicture = getRequest().getParameter("adPicture");
       		String rst = validateParm(rName, Amount, totalNum, reTimes, effectiveDate, isAllday, isSendAll, mainReType);
       		if(!"".equals(rst)){
			   	 result.put("code", 0);
		         result.put("msg", rst);
		         responseBody(result);
		         return;
       		}
       		//发送时间判断和校验
    		String period1 = "";
    		String period2 = "";
    		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		dateFormat.setLenient(false);
    		if("0".equals(isAllday)){
    			if(period.indexOf("和")>-1){
    				period1 = period.split("和")[0];
    				period2 = period.split("和")[1];
    				try{
    				Date date1 = dateFormat.parse("2017-01-01 "+period1.split("-")[0].trim()+":00");
    				Date date2 = dateFormat.parse("2017-01-01 "+period1.split("-")[1].trim()+":00");
    				Date date3 = dateFormat.parse("2017-01-01 "+period2.split("-")[0].trim()+":00");
    				Date date4 = dateFormat.parse("2017-01-01 "+period2.split("-")[1].trim()+":00");
    				if(!date1.before(date2)||!date3.before(date4)){
	   			   		 result.put("code", 0);
				         result.put("msg", "发放开始时间必须小于结束时间");
				         responseBody(result);
				         return;
    				}
    				if(date2.before(date4)){
    					if(date3.before(date2)){
   	   			   		 result.put("code", 0);
   				         result.put("msg", "发放时间不能相同或重叠");
   				         responseBody(result);
   				         return;
    					}
    				}
    				if(date2.after(date4)){
    					if(date1.before(date4)){
      	   			   		 result.put("code", 0);
      				         result.put("msg", "发放时间不能相同或重叠");
      				         responseBody(result);
      				         return;
       					}
    				}	
    				}catch(ParseException pe){
	   			   		 result.put("code", 0);
				         result.put("msg", "发放时间格式校验失败，请重新设置正确时间");
				         responseBody(result);
				         return;
    				}
    			}else{
    				period1 = period;
    				try{
    				Date date1 = dateFormat.parse("2017-01-01 "+period1.split("-")[0].trim()+":00");
    				Date date2 = dateFormat.parse("2017-01-01 "+period1.split("-")[1].trim()+":00");
    				if(!date1.before(date2)){
	   			   		 result.put("code", 0);
				         result.put("msg", "发放开始时间必须小于结束时间");
				         responseBody(result);
				         return;
    				}
    				}catch(ParseException pe){
	   			   		 result.put("code", 0);
				         result.put("msg", "发放时间格式校验失败，请重新设置正确时间");
				         responseBody(result);
				         return;
    				}
    			}
    		}
    		//红包类型判断 
    		BigDecimal AmountNum = new BigDecimal(Amount);
			int totalNumInt = Integer.parseInt(totalNum);
    		if("1".equals(mainReType)){
    			AmountNum = AmountNum.multiply(new BigDecimal(totalNumInt));
    		}
    		AmountNum = AmountNum.setScale(2, BigDecimal.ROUND_HALF_UP);
    		if(adPicture==null||"".equals(adPicture)){
    			adPicture = "/static/images/admin/wallet/dehb_03.jpg";
    		}
    		String reqPreUrl = WebUtil.getReqPreUrl(getRequest());
//			File file = getUpload();
//			if(file!=null){
//		    	String fileName = getUploadFileName();
//				result = UploadUtil.uplodeFile(file,fileName,REDENVPICPATH);
//				if (!"1".equals(result.get("code").toString())) {
//		        	responseBody(result);
//		        	return;
//				}
//				adPicture = result.get("agtAttr").toString();
//			}
       		result = redEnvService.addRedEnv(opt,rName,AmountNum,totalNumInt,Integer.parseInt(reTimes),effectiveDate,period1,period2,
       				isAllday,isSendAll,agentCodes,communityIds,buildingIds,unitIds,roomIds,mainReType,cUrl,adPicture,reqPreUrl);

        	responseBody(result);
       } 
       

   	public boolean isNumeric(String str){ 
   		   Pattern pattern = Pattern.compile("^(?!0(\\d|\\.0+$|$))\\d+(\\.\\d{1,2})?$"); 
   		   Matcher isNum = pattern.matcher(str);
   		   if( !isNum.matches() ){
   		       return false; 
   		   } 
   		   return true; 
   		}
        
    public void uploadFile() throws Exception{
   		result = new HashMap<String, Object>();
		File file = getUpload();
		String fileUrl = "";
		if(file!=null){
	    	String fileName = getUploadFileName();
			result = UploadUtil.uplodeFile(file,fileName,REDENVPICPATH);
			if (!"1".equals(result.get("code").toString())) {
	        	responseBody(result);
	        	return;
			}
			fileUrl = result.get("agtAttr").toString();
			result.put("fileUrl", fileUrl);
		}else{
			result.put("code", 0);
			result.put("msg", "请选择图片");			
		}
    	responseBody(result);    	
    }   
    private CRoom cRoom = new CRoom();

    @Override
    public CRoom getModel() {
        return cRoom;
    }
}
